package cn.iotab.iotkit.transport.api.access.model.custom.property;

import cn.iotab.iotkit.transport.api.access.model.custom.ProtocolConstant;
import cn.iotab.iotkit.transport.api.access.model.message.CommonDeviceMessage;
import cn.iotab.iotkit.transport.api.access.model.message.OriginMessage;
import cn.iotab.iotkit.transport.api.common.id.DeviceMessageKey;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 读取设备属性消息, 方向: 平台->设备
 * <p>
 * 下发指令后,设备需要回复指令{@link PropertyReadMessageReply}
 *
 * @author zhouhao
 * @see PropertyReadMessageReply
 * @since 1.0.0
 */
@Slf4j
public class PropertyReadMessage extends CommonDeviceMessage {

    /**
     * property后缀，拼接在prop.后面
     */
    @Getter
    @Setter
    private String propertySuffix;
    /**
     * 要读取的属性列表,协议包可根据实际情况处理此参数,
     * 有的设备可能不支持读取指定的属性,则直接读取全部属性返回即可
     */
    private List<String> properties = new ArrayList<>();

    public void addProperties(List<String> properties) {
        this.properties.addAll(properties);
    }

    public List<String> getProperties() {
        return properties;
    }

    @Override
    public void fromOriginMessage(String productKey, String deviceId, OriginMessage message) {
        super.fromOriginMessage(productKey, deviceId, message);
        propertySuffix = getOriginType().substring(ProtocolConstant.PROP_PREFIX.length());
        JSONArray props = getJsonParam().getJSONArray(ProtocolConstant.KEY_PROP);
        if (props == null) {
            DeviceMessageKey key = DeviceMessageKey.of(productKey, deviceId, message.getId());
            log.warn("PropertyGetMessage has no props: {}", key);
            return;
        }
        //
        this.properties = props.toJavaList(String.class);
    }

    @Override
    public OriginMessage toOriginMessage() {
        if (propertySuffix == null || propertySuffix.isEmpty()) {
            throw new IllegalArgumentException("propertySuffix is null or empty");
        }
        String tp = ProtocolConstant.PROP_PREFIX + propertySuffix;
        setOriginType(tp);
        //
        JSONObject object = new JSONObject();
        object.put(ProtocolConstant.KEY_PROP, properties);
        setJsonParam(object);
        return super.toOriginMessage();
    }

}
